package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 设置字符集编码方式
 * @ClassName: CharacterEncodingFilter 
 * @Description: TODO
 * @author zyk
 */
public class CharacterEncodingFilter implements Filter {

	protected FilterConfig filterConfig = null;
	protected String encoding = "UTF-8";
    /**
     * Default constructor. 
     */
    public CharacterEncodingFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		filterConfig = null;
		encoding = null;
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if (encoding != null) {
			// 设置request和response的编程格式
			request.setCharacterEncoding(this.encoding);
			response.setContentType("text/html;charset=utf-8");
			response.setCharacterEncoding("utf-8");
		}
		// 继续执行下一个过滤器
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		this.filterConfig = fConfig;
		this.encoding = filterConfig.getInitParameter("encoding");
	}

}
